package com.lsh.payment.api.service.exception;

import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.protocol.rest.RpcExceptionMapper;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.lsh.payment.api.model.basevo.BaseResponse;
import com.lsh.payment.api.model.basevo.ExceptionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.Response;
import java.util.Date;

/**
 * Project Name: lsh-payment
 * Author: peter
 * 北京链商电子商务有限公司
 * Desc: 业务异常mapper
 * Package Name:
 * Time: 2018-06-05 下午2:51
 */
public class ValidationExceptionMapper extends RpcExceptionMapper {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Response toResponse(RpcException e) {
        return this.handleConstraintViolationException((ConstraintViolationException) e.getCause());
    }

    @Override
    protected Response handleConstraintViolationException(ConstraintViolationException cve) {
        StringBuilder builder = new StringBuilder("【请求参数错误】");
        for (ConstraintViolation cv : cve.getConstraintViolations()) {
            builder.append("[").append(cv.getPropertyPath().toString()).append(" - ").append(cv.getMessage()).append(" ]\n");
        }
        builder.deleteCharAt(builder.length() - 1);
        String message = builder.toString();
        logger.error("request param is error! " + message);
        return Response.status(Response.Status.OK)
                .entity(new BaseResponse(Integer.valueOf(ExceptionStatus.E1001001.getCode()),message,new Date()))
                .type(ContentType.APPLICATION_JSON_UTF_8)
                .header("X-Frame-Options","SAMEORIGIN")
                .build();
    }


}
